package cn.serein.charging.user.service.impl;

import cn.serein.charging.common.utils.JsonUtils;
import cn.serein.charging.user.dao.repository.WechatLoginRepository;
import cn.serein.charging.user.pojo.WechatData;
import cn.serein.charging.user.pojo.po.UserPO;
import cn.serein.charging.user.service.WxLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class WxLoginServiceImpl implements WxLoginService {

    private String appId = "wx411297a11c1ff044";

    private String appSecret = "27a9461aa058b09e0dfb4afe2fb09670";

    @Autowired
    private WechatLoginRepository wechatLoginRepository;

    @Override
    public Integer login(String code, String nickName) {
        String openId = getOpenId(code);
        if(openId != null){
            //
            UserPO userPO = wechatLoginRepository.getUserByOpenId(openId);

            // 如果不存在 插入
            if(userPO == null){
                userPO = new UserPO();
                userPO.setNickName(nickName);
                userPO.setWxOpenId(openId);

                return wechatLoginRepository.save(userPO);
            }else{
                return userPO.getId();
            }
        }

        return -1;
    }

    @Autowired
    private RestTemplate restTemplate;

    private String getOpenId(String code) {

        // 通过code 调用微信的第三方接口获取用户的openId
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + appId +
                "&secret=" + appSecret +
                "&js_code=" + code +
                "&grant_type=authorization_code";

            String openId = restTemplate.getForObject(url, String.class);
            log.debug("得到的openId:{}", openId);

        WechatData wxchatData = JsonUtils.fromJson(openId, WechatData.class);

        if (wxchatData != null){
            return wxchatData.getOpenid();
        }

        return null;

    }
}
